package com.cl.esjsoup.jsoup;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AgeLogin {
    public static String LOGIN_URL = "https://www.agefans.vip/accounts/login/";
    public static String USER_AGENT = "User-Agent";
    public static String USER_AGENT_VALUE = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";

    public static String USERNAME = "X";
    public static String PWD = "X";

    public static void main(String[] args) {
        Connection.Response response = getCookies();
        Map<String, String> cookies = response.cookies();
        System.out.println("cookies  " + cookies);
        Connection connect = Jsoup.connect("https://www.agefans.vip/accounts/profile/");
        connect.header(USER_AGENT, USER_AGENT_VALUE);
        connect.cookies(cookies);
        Connection.Response execute = null;
        try {
            execute = connect.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert execute != null;
        System.out.println("multiHeaders  " + execute.multiHeaders());
        System.out.println("cookies  " + execute.cookies());
        System.out.println(execute.body());
    }

    private static Connection.Response getCookies() {
        Connection connect = Jsoup.connect(LOGIN_URL);
        connect.header(USER_AGENT, USER_AGENT_VALUE);
        Connection.Response execute = null;
        try {
            execute = connect.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert execute != null;
        Document parse = Jsoup.parse(execute.body());
        Elements accountForm = parse.getElementsByClass("account_form");
        Elements input = accountForm.get(0).getElementsByTag("input");
        HashMap<String, String> map = new HashMap<>();
        for (Element element : input) {
            String name = element.attr("name");
            String value = element.attr("value");
            if (name.equals("username")) {
                value = USERNAME;
            } else if (name.equals("password")) {
                value = PWD;
            }

            map.put(name, value);
        }
        Connection.Response response = null;
        try {
            response = connect.ignoreContentType(true)
                    .followRedirects(true)
                    .method(Connection.Method.POST)
                    .data(map)
                    .cookies(execute.cookies())
                    .execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}
